//
//  AcvChoosePosController.m
//  ZiJinLian
//
//  Created by 震霄 张 on 2018/4/5.
//  Copyright © 2018年 lzy. All rights reserved.
//

#import "AcvChoosePosController.h"
#import "ActivityChoosePosModel.h"
#import "ZFSeatSelectionView.h"
#import "ActivityPostionRowModel.h"
#import "ZFSeatsModel.h"
#import "ZFSeatSelectionView.h"
#import "ZFSeatSelectionTool.h"
#import "ActivitySeatHeaderView.h"
#import "SelectSeatView.h"
#import "ZFSeatButton.h"
#import "ActivityConfrimController.h"
#import "AcvConfirmModel.h"
#import "JYAlertView.h"
#import "AcvOrderModel.h"
#import "PayViewController.h"

#define MAXSEATSNUM 5
#define padding 15

@interface AcvChoosePosController ()<SelectSeatViewDelegate>
@property (nonatomic,strong)ActivityChoosePosModel *model;

/**按钮数组*/
@property (nonatomic, strong) NSMutableArray *selecetedSeats;

@property (nonatomic,strong) NSMutableDictionary *allAvailableSeats;//所有可选的座位

@property (nonatomic,strong) NSMutableArray *seatsModelArray;

@property (nonatomic,weak)ActivitySeatHeaderView *headView;

@property (nonatomic,weak)UIScrollView *seatsScrollView;

@property (nonatomic,weak)UIButton *confirmBtn;

@property (nonatomic,weak)UIScrollView *bgScrolliew;

@property (nonatomic,weak)ZFSeatSelectionView *selectionView;

@end

@implementation AcvChoosePosController

- (void)viewDidLoad {
    [super viewDidLoad];
	[self setupUI];
//	[self setupData];
}

-(void)viewWillAppear:(BOOL)animated
{
	[super viewWillAppear:animated];
	[self setupData];

}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

-(void)setupUI
{
	self.navigationItem.title = @"供养选位";
	
	UIButton *confirmBtn = [UIButton buttonWithType:UIButtonTypeCustom];
	confirmBtn.width = screen_Width;
	confirmBtn.height = 50;
	confirmBtn.x = 0;
	confirmBtn.y = screen_Height - RD_NavBarHeight - 50;
//	[confirmBtn setBackgroundImage:[UIImage imageNamed:@"btn_selected_s"] forState:UIControlStateNormal];
	[confirmBtn setBackgroundColor:Red_Color];
	[confirmBtn setTitle:@"确认选位" forState:UIControlStateNormal];
	confirmBtn.titleLabel.textColor = [UIColor whiteColor];
	confirmBtn.titleLabel.font = [UIFont systemFontOfSize:14];
	[confirmBtn addTarget:self action:@selector(confirmBtnCLick) forControlEvents:UIControlEventTouchUpInside];
	
	[self.view addSubview:confirmBtn];
	self.confirmBtn = confirmBtn;
	
	UIScrollView *bgScrolliew = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, screen_Width, screen_Height-RD_NavBarHeight - confirmBtn.height)];
	bgScrolliew.showsHorizontalScrollIndicator = NO;
	bgScrolliew.showsVerticalScrollIndicator = NO;
	self.bgScrolliew = bgScrolliew;
	[self.view addSubview:bgScrolliew];
	
	ActivitySeatHeaderView *headView = [ActivitySeatHeaderView activitySeatHeaderView];
	headView.frame = CGRectMake(0, 0, screen_Width, 100);
//	[self.view addSubview:headView];
	[self.bgScrolliew addSubview:headView];
	self.headView = headView;
	
	UILabel *infoLabel = [[UILabel alloc]initWithFrame:CGRectMake(15, CGRectGetMaxY(self.headView.frame)+400+10, screen_Width-30, 20)];
	infoLabel.text = @"已选位置";
	infoLabel.font = [UIFont systemFontOfSize:12];
	infoLabel.textColor = TextColor3;
//	[self.view addSubview:infoLabel];
	[self.bgScrolliew addSubview:infoLabel];
	
	UIScrollView *seatsScrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(infoLabel.frame)+10, screen_Width, 40)];
	seatsScrollView.showsVerticalScrollIndicator = NO;
	seatsScrollView.showsHorizontalScrollIndicator = NO;
	self.seatsScrollView = seatsScrollView;
	seatsScrollView.contentSize = CGSizeMake(MAXSEATSNUM * (80+15), 40);
//	[self.view addSubview:seatsScrollView];
	[self.bgScrolliew addSubview:seatsScrollView];
	
	
	self.bgScrolliew.contentSize = CGSizeMake(screen_Width, headView.height + 400 + 10 + infoLabel.height+10+seatsScrollView.height+10);
	
}

-(void)confirmBtnCLick
{
	NSLog(@"confirmBtnCLick");
	
	NSMutableArray *seats = [NSMutableArray array];
	for (int i = 0; i<self.selecetedSeats.count; i++) {
		ZFSeatButton *btnModel = self.selecetedSeats[i];
		ZFSeatModel *model = btnModel.seatmodel;
		[seats addObject:[NSString stringWithFormat:@"%ld",model.ID]];
	}
	__weak typeof(self) weakSelf = self;
	NSMutableDictionary *dic=[[NSMutableDictionary   alloc]init];
	dic[@"userId"]=[ZJUserDefaultsTools getCurrentUserID];
	dic[@"nodeIds"] = [Utils jsonFromArray:seats];
	[self doHttpRequestWithApi:API_COMFIRM_SEAT_LIST method:GET dic:dic successBlock:^(NSDictionary *dic) {
		NSLog(@"%@",dic);
		if ([dic[@"status"] integerValue] == 0) {
			AcvConfirmModel *confimModel = [AcvConfirmModel mj_objectWithKeyValues:dic[@"data"]];
			ActivityConfrimController *vc = [[ActivityConfrimController alloc]init];
			vc.model = confimModel;
			vc.ID = self.ID;
			[weakSelf.navigationController pushViewController:vc animated:YES];
			
		}else{
			[MBProgressHUD showError:dic[@"msg"]];
			
		}
	}];
	
}

-(void)setupData
{
	NSMutableDictionary *dic=[[NSMutableDictionary   alloc]init];
	dic[@"id"]=[NSString stringWithFormat:@"%ld",self.ID];
	dic[@"userId"] = [ZJUserDefaultsTools getCurrentUserID];
	__weak typeof(self) weakSelf = self;
	[self doHttpRequestWithApi:API_CHOOSEPOS_LIST method:GET dic:dic successBlock:^(NSDictionary *dic) {
		NSLog(@"%@",dic);
		if ([dic[@"status"] integerValue] == 0) {
			self.model = [ActivityChoosePosModel mj_objectWithKeyValues:dic[@"data"]];
			self.headView.model = self.model;
			
			self.seatsModelArray = [self getDataArr];
			[weakSelf initSelectionView:self.seatsModelArray];
		}else if([dic[@"status"] integerValue] == 1){
			[MBProgressHUD showError:dic[@"msg"]];
		}else if ([dic[@"status"] integerValue] == 2){
			//锁单，msg：跳转支付的单号
			NSString *msg = dic[@"msg"];
			[JYAlertView showAlertViewWithMessage:@"是否前往已有订单" titleArr:@[@"取消",@"确定"] titleColors:@[[UIColor blackColor],[UIColor redColor]] actionHandler:^(NSInteger tag) {
				if (tag == 0) {
					//取消
					AcvOrderModel *orderM = [AcvOrderModel mj_objectWithKeyValues:msg];
					__weak typeof(self) weakSelf = self;
					NSMutableDictionary *dic=[[NSMutableDictionary   alloc]init];
					dic[@"userId"]=[ZJUserDefaultsTools getCurrentUserID];
					dic[@"orderId"] = orderM.payNo;
					[self doHttpRequestWithApi:API_CANCEL_ORDER_LIST method:GET dic:dic successBlock:^(NSDictionary *dic) {
						NSLog(@"%@",dic);
						if ([dic[@"status"] integerValue] == 0) {
							[weakSelf setupData];
							
						}else{
							[MBProgressHUD showError:dic[@"msg"]];
						}
					}];
				}else{
					//使用
					AcvOrderModel *orderM = [AcvOrderModel mj_objectWithKeyValues:msg];
					PayViewController *vc=[[PayViewController alloc]init];
					vc.orderSn = orderM.payNo;
					vc.orderDic= [NSMutableDictionary dictionaryWithDictionary:[Utils dictionaryWithJsonString:msg]];
;					vc.isNewUrl = YES;
					[self.navigationController pushViewController:vc animated:YES];
				}
			}];
			
			
		}else if ([dic[@"status"] integerValue] == 3){
			//锁座：msg：跳转提交供养的供养位置id list
			NSString *msg = dic[@"msg"];
			[JYAlertView showAlertViewWithMessage:@"是否使用已选座位" titleArr:@[@"取消",@"确定"] titleColors:@[[UIColor blackColor],[UIColor redColor]] actionHandler:^(NSInteger tag) {
				NSLog(@"tag = %ld",tag);
				if (tag == 0) {
					//取消
//					[self.selecetedSeats removeAllObjects];
					[self.seatsScrollView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];

					__weak typeof(self) weakSelf = self;
					NSMutableDictionary *dic=[[NSMutableDictionary   alloc]init];
					dic[@"userId"]=[ZJUserDefaultsTools getCurrentUserID];
					dic[@"nodeIds"] = msg;
					[self doHttpRequestWithApi:API_CANCEL_SEAT_LIST method:GET dic:dic successBlock:^(NSDictionary *dic) {
						NSLog(@"%@",dic);
						if ([dic[@"status"] integerValue] == 0) {
							[weakSelf setupData];
							
						}else{
							[MBProgressHUD showError:dic[@"msg"]];
						}
					}];
					
					
				}else{
					//使用
					__weak typeof(self) weakSelf = self;
					NSMutableDictionary *dic=[[NSMutableDictionary   alloc]init];
					dic[@"userId"]=[ZJUserDefaultsTools getCurrentUserID];
					dic[@"nodeIds"] = msg;
					[self doHttpRequestWithApi:API_COMFIRM_SEAT_LIST method:GET dic:dic successBlock:^(NSDictionary *dic) {
						NSLog(@"%@",dic);
						if ([dic[@"status"] integerValue] == 0) {
							AcvConfirmModel *confimModel = [AcvConfirmModel mj_objectWithKeyValues:dic[@"data"]];
							ActivityConfrimController *vc = [[ActivityConfrimController alloc]init];
							vc.model = confimModel;
							vc.ID = self.ID;
							[weakSelf.navigationController pushViewController:vc animated:YES];
							
						}else{
							[MBProgressHUD showError:dic[@"msg"]];
							
						}
					}];
					
					
				}
			}];
			
			
		};
	}];
}


//创建选座模块
-(void)initSelectionView:(NSMutableArray *)seatsModelArray{
	__weak typeof(self) weakSelf = self;
	ZFSeatSelectionView *selectionView = [[ZFSeatSelectionView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(self.headView.frame),[UIScreen mainScreen].bounds.size.width, 400)SeatsArray:seatsModelArray HallName:self.model.wallName seatBtnActionBlock:^(NSMutableArray *selecetedSeats, NSMutableDictionary *allAvailableSeats, NSString *errorStr)
	{
		NSLog(@"=====%zd个选中按钮===========%zd个可选座位==========errorStr====%@=========",selecetedSeats.count,allAvailableSeats.count,errorStr);
		if (errorStr) {
			//错误信息
			[self showMessage:errorStr];
		}else{
			//储存选好的座位及全部可选座位
			weakSelf.allAvailableSeats = allAvailableSeats;
			weakSelf.selecetedSeats = selecetedSeats;
			
			[weakSelf updateSelectSeatView];
			
		}
	}];
	
//	[self.view addSubview:selectionView];
	[self.bgScrolliew addSubview:selectionView];
	self.selectionView = selectionView;
}

-(void)updateSelectSeatView
{
	[self.seatsScrollView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
	CGFloat totalPrice = 0;
	for (int i = 0; i<self.selecetedSeats.count; i++) {
		ZFSeatButton *btnModel =  self.selecetedSeats[i];
		ZFSeatModel *model = btnModel.seatmodel;
		totalPrice += [model.price floatValue];
		SelectSeatView *seatView = [SelectSeatView selectSeatView];
		seatView.model = model;
		seatView.delegate = self;
		seatView.frame = CGRectMake(padding + i*(80+padding), 0, 80, 40);
		[self.seatsScrollView addSubview:seatView];
	}
	
	[self.confirmBtn setTitle:[NSString stringWithFormat:@"¥%.2f确认选座",totalPrice] forState:UIControlStateNormal];

}

-(NSMutableArray *)getDataArr
{
	//数据回来初始化选座模块
	NSMutableArray *modelsArr = [NSMutableArray array];
	
	//转化成行排的
	NSMutableArray *rows = [NSMutableArray array];
	for (int m = 0; m<self.model.row; m++) {
		for (int n = 0; n<self.model.nodeList.count; n++) {
			ActivityPositionModel *pmodel = self.model.nodeList[n];
			//--
			ZFSeatModel *seatModel = [[ZFSeatModel alloc]init];
			seatModel.columnId = pmodel.columnId;
			seatModel.seatNo = pmodel.seatNo;
			seatModel.st = pmodel.st;
			seatModel.rowId = [NSString stringWithFormat:@"%ld",pmodel.row];
			seatModel.ID = pmodel.ID;
			seatModel.price = pmodel.price;
			seatModel.priceStatus = pmodel.priceStatus;
			seatModel.sellStatus = pmodel.sellStatus;
			//--
			if (pmodel.row == m+1) {
				[rows addObject:seatModel];
			}

		}
		
//		ActivityPostionRowModel *rowModel = [[ActivityPostionRowModel alloc]init];
		ZFSeatsModel *rowModel = [[ZFSeatsModel alloc]init];
		rowModel.columns = [rows copy];
		ZFSeatModel *postModel = rows[0];
		rowModel.rowId = postModel.rowId;
		rowModel.rowNum = [NSNumber numberWithInteger:[postModel.rowId integerValue]];
		[modelsArr addObject:rowModel];
		[rows removeAllObjects];
	}
	return modelsArr;
	
}
#pragma mark selectseatViewDelegate
-(void)deleteSeat:(ZFSeatModel *)model
{
	NSInteger delectIndex = -1;
	for (int i = 0; i<self.selecetedSeats.count; i++) {
		ZFSeatButton *bModel = self.selecetedSeats[i];
		if (bModel.seatmodel.ID == model.ID) {
			delectIndex = i;
			break;
		}
	}
	
	NSLog(@"删除第%ld个座位",delectIndex);
	
	[self.selectionView deleteSelectSeat:self.selecetedSeats[delectIndex]];
//	[self.selecetedSeats removeObjectAtIndex:delectIndex];

	
	
}

@end
